package com.rjwh.dingdong.client.service;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.NotificationCompat;
import android.util.Log;

import com.aishua.lib.utils.AsStrUtils;
import com.alibaba.fastjson.JSON;
import com.igexin.sdk.GTIntentService;
import com.igexin.sdk.PushConsts;
import com.igexin.sdk.PushManager;
import com.igexin.sdk.message.FeedbackCmdMessage;
import com.igexin.sdk.message.GTCmdMessage;
import com.igexin.sdk.message.GTTransmitMessage;
import com.igexin.sdk.message.SetTagCmdMessage;
import com.rjwh.dingdong.client.R;
import com.rjwh.dingdong.client.activity.webbrowser.OaGameActivity;
import com.rjwh.dingdong.client.application.AppManager;
import com.rjwh.dingdong.client.application.MyApplication;
import com.rjwh.dingdong.client.bean.localbean.PushMsgData;
import com.rjwh.dingdong.client.constant.LocalConstant;
import com.rjwh.dingdong.client.network.ApiRequest;
import com.rjwh.dingdong.client.receiver.NotificationReceiver;
import com.rjwh.dingdong.client.util.AppUtil;
import com.rjwh.dingdong.client.util.LogUtil;
import com.rjwh.dingdong.client.util.UrlUtil;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 继承 AppPushIntentService 接收来自个推的消息, 所有消息在线程中回调, 如果注册了该服务, 则务必要在 AndroidManifest中声明, 否则无法接受消息<br>
 * onReceiveMessageData 处理透传消息<br>
 * onReceiveClientId 接收 cid <br>
 * onReceiveOnlineState cid 离线上线通知 <br>
 * onReceiveCommandResult 各种事件处理回执 <br>
 */
public class AppPushIntentService extends GTIntentService {

    private static final String TAG = AppPushIntentService.class.getSimpleName();

    /**
     * 为了观察透传数据变化.
     */
    private static int cnt;

    public AppPushIntentService() {

    }

    @Override
    public void onReceiveServicePid(Context context, int pid) {
        LogUtil.d(TAG, "onReceiveServicePid -> " + pid);
    }

    @Override
    public void onReceiveMessageData(Context context, GTTransmitMessage msg) {
        String appid = msg.getAppid();
        String taskid = msg.getTaskId();
        String messageid = msg.getMessageId();
        byte[] payload = msg.getPayload();
        String pkg = msg.getPkgName();
        String cid = msg.getClientId();

        // 第三方回执调用接口，actionid范围为90000-90999，可根据业务场景执行
        boolean result = PushManager.getInstance().sendFeedbackMessage(context, taskid, messageid, 90001);
        LogUtil.d(TAG, "call sendFeedbackMessage = " + (result ? "success" : "failed"));

        LogUtil.d(TAG, "onReceiveMessageData -> " + "appid = " + appid + "\ntaskid = " + taskid + "\nmessageid = " + messageid + "\npkg = " + pkg
                + "\ncid = " + cid);

        if (payload == null) {
            LogUtil.e(TAG, "receiver payload = null");
        } else {
            String data = new String(payload);
            LogUtil.d(TAG, "receiver payload = " + data);

            // 测试消息为了观察数据变化
            if (data.equals("收到一条透传测试消息")) {
                data = data + "-" + cnt;
                cnt++;
            }
            doAction(context, data);
        }

        LogUtil.d(TAG, "----------------------------------------------------------------------------------------------");
    }

    @Override
    public void onReceiveClientId(Context context, String clientid) {
        LogUtil.e(TAG, "onReceiveClientId -> " + "clientid = " + clientid);
        MyApplication.spUtil.setStrPreference(MyApplication.getInstance(), LocalConstant.SP_CLIENTID, clientid);
        try {
            ApplicationInfo appInfo = context.getPackageManager()
                    .getApplicationInfo(context.getPackageName(),
                            PackageManager.GET_META_DATA);
            String msg = appInfo.metaData.getString("PUSH_APPID");
            LogUtil.e(TAG, "PUSH_APPID:" + msg);
            if (!AsStrUtils.isEmpty(msg)) {
                LogUtil.d(TAG, "绑定推送");
                ApiRequest.pushBindingForAppId(msg, clientid, null);
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onReceiveOnlineState(Context context, boolean online) {
        LogUtil.d(TAG, "onReceiveOnlineState -> " + (online ? "online" : "offline"));
    }

    @Override
    public void onReceiveCommandResult(Context context, GTCmdMessage cmdMessage) {
        LogUtil.d(TAG, "onReceiveCommandResult -> " + cmdMessage);

        int action = cmdMessage.getAction();

        if (action == PushConsts.SET_TAG_RESULT) {
            setTagResult((SetTagCmdMessage) cmdMessage);
        } else if ((action == PushConsts.THIRDPART_FEEDBACK)) {
            feedbackResult((FeedbackCmdMessage) cmdMessage);
        }
    }

    private void setTagResult(SetTagCmdMessage setTagCmdMsg) {
        String sn = setTagCmdMsg.getSn();
        String code = setTagCmdMsg.getCode();

        String text = "设置标签失败, 未知异常";
        switch (Integer.valueOf(code)) {
            case PushConsts.SETTAG_SUCCESS:
                text = "设置标签成功";
                break;

            case PushConsts.SETTAG_ERROR_COUNT:
                text = "设置标签失败, tag数量过大, 最大不能超过200个";
                break;

            case PushConsts.SETTAG_ERROR_FREQUENCY:
                text = "设置标签失败, 频率过快, 两次间隔应大于1s且一天只能成功调用一次";
                break;

            case PushConsts.SETTAG_ERROR_REPEAT:
                text = "设置标签失败, 标签重复";
                break;

            case PushConsts.SETTAG_ERROR_UNBIND:
                text = "设置标签失败, 服务未初始化成功";
                break;

            case PushConsts.SETTAG_ERROR_EXCEPTION:
                text = "设置标签失败, 未知异常";
                break;

            case PushConsts.SETTAG_ERROR_NULL:
                text = "设置标签失败, tag 为空";
                break;

            case PushConsts.SETTAG_NOTONLINE:
                text = "还未登陆成功";
                break;

            case PushConsts.SETTAG_IN_BLACKLIST:
                text = "该应用已经在黑名单中,请联系售后支持!";
                break;

            case PushConsts.SETTAG_NUM_EXCEED:
                text = "已存 tag 超过限制";
                break;

            default:
                break;
        }

        LogUtil.d(TAG, "settag result sn = " + sn + ", code = " + code + ", text = " + text);
    }

    private void feedbackResult(FeedbackCmdMessage feedbackCmdMsg) {
        String appid = feedbackCmdMsg.getAppid();
        String taskid = feedbackCmdMsg.getTaskId();
        String actionid = feedbackCmdMsg.getActionId();
        String result = feedbackCmdMsg.getResult();
        long timestamp = feedbackCmdMsg.getTimeStamp();
        String cid = feedbackCmdMsg.getClientId();

        LogUtil.d(TAG, "onReceiveCommandResult -> " + "appid = " + appid + "\ntaskid = " + taskid + "\nactionid = " + actionid + "\nresult = " + result
                + "\ncid = " + cid + "\ntimestamp = " + timestamp);
    }

    private void doAction(Context context, String data) {
        try {
            PushMsgData pushMsgData = JSON.parseObject(data, PushMsgData.class);
            if (pushMsgData != null) {
                String actionid = pushMsgData.getActionid();
                LogUtil.d(TAG, "actionid:" + actionid);
                String actionurl = pushMsgData.getActionurl();
                String content = pushMsgData.getContent();
                String title = pushMsgData.getTitle();

                if (AsStrUtils.isEmpty(actionid) || AsStrUtils.isEmpty(actionurl) || AsStrUtils.isEmpty(content) || AsStrUtils.isEmpty(title)) {
                    return;
                }

                //当前APP处于前台
                if (AppUtil.isBackground(context)) {
                    LogUtil.e(TAG, "isBackground = true");
                    if (AppUtil.isForeground(context, OaGameActivity.class.getName())) {
                        LogUtil.e(TAG, "isBackground   &&   OaGameActivity  isForeground ");
                        sendNotify(context, title, content, actionurl, actionid);
                    } else {
                        showDialog(context, title, content, actionurl, actionid);
                    }
                } else {
                    LogUtil.e(TAG, "isBackground = false");
                    sendNotify(context, title, content, actionurl, actionid);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void sendNotify(final Context context, String title, String content, final String actionurl, final String actionid) {

        //设置点击通知栏的动作为启动另外一个广播
        Intent broadcastIntent = new Intent(context, NotificationReceiver.class);
        broadcastIntent.putExtra("actionurl", actionurl);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        Bitmap bmp = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon_logo);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
        builder.setAutoCancel(true)
                .setContentTitle(title)
                .setContentText(content)
                .setTicker(title + content)
                .setContentIntent(pendingIntent)
                .setDefaults(Notification.DEFAULT_ALL)
                .setLargeIcon(bmp)
                .setColor(ContextCompat.getColor(context, R.color.transparency));
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            builder.setSmallIcon(R.drawable.icon_push_small);
        } else {
            builder.setSmallIcon(R.drawable.icon_logo);
        }
        LogUtil.d(TAG, "showNotification");
        NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        manager.notify(
//                Integer.parseInt(actionid)
                getNotificationID()
                , builder.build());
        LogUtil.d(TAG, "NotificationID.getID():" + getNotificationID());
        MyApplication.spUtil.setIntPreference(context, LocalConstant.SP_NOTIFICATIONID, getNotificationID());
    }

    //生成通知id
    private int getNotificationID() {
        int defaultID = MyApplication.spUtil.getIntPreferenceByParamName(MyApplication.getInstance(), LocalConstant.SP_NOTIFICATIONID);
        LogUtil.d(TAG, "defaultID:" + defaultID);
        AtomicInteger c = new AtomicInteger(defaultID);
        return c.incrementAndGet();
    }

    private void showDialog(final Context context, final String title, final String content, final String actionurl, final String actionid) {
        final Activity activity = AppManager.getAppManager().currentActivity();

        if (activity != null && !activity.isFinishing()) {
            LogUtil.e(TAG, "activity: " + activity.getClass());
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    AlertDialog dialog = new AlertDialog.Builder(activity)
                            .setTitle(title)
                            .setMessage(content)
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                    UrlUtil.handelUrl(activity, actionurl, true);
                                }
                            })
                            .show();
                }
            });
        } else {
            sendNotify(context, title, content, actionurl, actionid);
        }

    }

}
